﻿using System;
using System.Collections.Generic;
using System.Text;

namespace POSPlus.BTxmlWriter
{
    public class Tree<TValue>
    {
        public Node<TValue> Root { get; private set; }

        public Tree(String key, TValue value)
        {
            Root = new Node<TValue>(key, value);
        }

        public Tree(Node<TValue> root)
        {
            Root = root;
        }
        public void AddNode(String path, Node<TValue> node)
        {
            String[] pathSplit = path.Substring(1).Split('/');
            Node<TValue> parent = Root;
            if (pathSplit.Length > 1)
            {
                foreach (String pathPart in pathSplit)
                {
                    if(!pathPart.Equals(Root.Name))
                        parent = parent.Children[pathPart];
                }
            }

            parent.AddChild(node);
        }

        public void AddAttribute(String path, String key, TValue value)
        {
            String[] pathSplit = path.Substring(1).Split('/');
            Node<TValue> parent = Root;
            for (int i = 1; i < pathSplit.Length; i++)
            {
                parent = parent.Children[pathSplit[i]];
            }

            parent.AddAttribute(key, value);
        }

        public string Traverse(Node<TValue> node)
        {
            string result = "";
            if (node.Children.Count < 1)
                return node.GetAncestory();
            else
            {
                foreach (Node<TValue> child in node.Children.Values)
                {
                    Console.Write("Test Line:" + child.GetAncestory() + "\n");
                    result += "\n" + Traverse(child);
                }
                return node.GetAncestory() + result;
            }
        }

        public Node<TValue> GetNode(string path)
        {
            String[] pathSplit = path.Substring(1).Split('/');
            Node<TValue> parent = Root;
            for (int i = 1; i < pathSplit.Length; i++)
            {
                parent = parent.Children[pathSplit[i]];
            }

            return parent;
        }
    }
}
